package org.dy.db.model;

import java.util.Collections;

public class Row extends TableHeader{
	

	public boolean valid(){
		for(FieldInfo field : fields){
			if(!field.valid())
				return false;
		}
		return true;
	}
	
	public String getFieldsString(int type){		
		return getFieldsString(type, true, false);
	}
	
	/**
	 * @param type	eg 0,1,2,3 => key=value,key,value,key=?
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getFieldsString(int type, boolean includePk, boolean pkEnd){	
		if(pkEnd)
			includePk = true;
		StringBuffer sb = new StringBuffer("");
		Collections.sort(fields);
		
		int count = 0;
		for (FieldInfo fi : fields) {
			count++;
			if((!includePk && fi.isPk) || (fi.isPk && pkEnd))
				continue;
			if(fi.value != null){
				
				switch(type){
				case 1 :
					sb.append(fi.name);
					break;
				case 2 :
					sb.append(fi.value);
					break;
				case 3 :
					sb.append(fi.name);
					sb.append("=");
					sb.append("?");
					break;
				default :
					sb.append(fi.name);
					sb.append("=");
					sb.append(fi.value);
					break;
				}
				if (count != fields.size())
					sb.append(",");
			}
		}	
		if(pkEnd){
			FieldInfo pi = getPkInfo();
			if(sb.length() > 0)
				sb.append(",");
			if(pi != null && pi.value != null){
				switch(type){
				case 1 :
					sb.append(pi.name);
					break;
				case 2 :
					sb.append(pi.value);
					break;
				case 3 :
					sb.append(pi.name);
					sb.append("=");
					sb.append("?");
					break;
				default :
					sb.append(pi.name);
					sb.append("=");
					sb.append(pi.value);
					break;
				}
			}
		}
		String rString = sb.toString();
		return rString.endsWith(",")?rString.substring(0, rString.length() - 1):rString;
	}
	
}
